﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BinAnalysisHelp;
using Newtonsoft.Json;
using XChipTool.Enties;
using System.Threading;
using System.IO;

namespace XChipTool
{
    public partial class BinIqEffectCopy : DevExpress.XtraEditors.XtraForm
    {
        public BinIqEffectCopy()
        {
            InitializeComponent();
        }

        public static List<BinBase> BinInList;
        public static List<BinBase> BinOutList;

        private bool isTest = true;

        //Flas加密模式0：MD5-64 1：MD5-128 2：Flash ID 3：other
        private byte FlashModes = 0;
        private List<byte> FlashbyteList = new List<byte>();
        /// <summary>
        /// 连接关系解析 Usb LoadSetting
        /// </summary>
        public static List<SettingFileIDInfo> usbInList;

        public static List<SettingFileIDInfo> usbOutList;

        public delegate void UpdateProgressBarDelegate(int position);

        private void UpdateProgressBar(int position)
        {
            if (progressBar.InvokeRequired)
            {
                progressBar.Invoke(new UpdateProgressBarDelegate(UpdateProgressBar), position);
            }
            else
            {
                progressBar.Position = position;
                progressBar.Refresh();
            }
        }
        /// <summary>
        /// 目标Bin文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog sfd = new OpenFileDialog();
                //设置文件类型 
                sfd.Filter = "导入BIN（*.bin）|*.bin";
                //设置默认文件类型显示顺序 
                sfd.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录 
                sfd.RestoreDirectory = true;
                if (sfd.ShowDialog() != DialogResult.OK) return;
                UpdateProgressBar(0);
                textEdit1.Text = sfd.FileName;
                WaitBefore.Start("请耐心等待...", "正在解析Bin");
                BinOutList = new List<BinBase>();
                BinOutList = BinHelp.BinToList(sfd.FileName);
                UpdateProgressBar(10);
                xc151_exManager xcmex = new xc151_exManager();
                var xclist = JsonConvert.DeserializeObject<List<xc151binparsing>>(xcmex.GetListToXc151Binparsing()).OrderBy(c => c.Id).ToList();
                ///*  File.WriteAllText("C:\\Users\\Adm*/inistrator\\Desktop\\1.txt", xcmex.GetListToXc151Binparsing());
                BinHelp.BinBaseToNode(BinOutList, xclist);
                UpdateProgressBar(20);
                BinOutList = BinHelp.BinBaseToIsp(BinOutList);
                UpdateProgressBar(30);
                BinHelp.SetModeIsp(ref BinOutList);
                UpdateProgressBar(80);
                var tlist = BinOutList.Where(c => !string.IsNullOrEmpty(c.note) && c.note.Contains("setting区1_31_") && !c.note.Contains("_en") && !c.module.Contains("Header")).ToList();

                if (tlist.Count() > 0)
                {
                    Setting1_31Parser s1_31 = new Setting1_31Parser();
                    s1_31.LoadSettingData(tlist.Select(c => c.original).ToList());
                    usbOutList = s1_31.GetFileIDInfo();
                    UpdateProgressBar(100);
                    if (isTest)
                    {
                        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        string fulloPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "usbtest");
                        if (!Directory.Exists(fulloPath))
                        {
                            Directory.CreateDirectory(fulloPath);
                        }
                        StringBuilder sbO = new StringBuilder();
                        foreach (var item in usbOutList)
                        {
                            sbO.Append($"{item.width} {item.height} {item.Type} {item.note}\r\n");
                        }
                        fulloPath = Path.Combine(fulloPath, "outList目标.txt");
                        File.WriteAllText(fulloPath, sbO.ToString());
                    }
                    //VerifyFlashCommunicationEncryption();

                }
                else
                {
                    UpdateProgressBar(0);
                    MessageBox.Show("Bin文件中不存在1_31文件，无法完成Bin解析工作，请检查Bin文件！");
                    return;
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                WaitBefore.Close();
            }
        }
        /// <summary>
        /// 已有Bin文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog sfd = new OpenFileDialog();
                //设置文件类型 
                sfd.Filter = "导入BIN（*.bin）|*.bin";
                //设置默认文件类型显示顺序 
                sfd.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录 
                sfd.RestoreDirectory = true;
                if (sfd.ShowDialog() != DialogResult.OK) return;
                memoEdit1.Text = sfd.FileName;

                WaitBefore.Start("请耐心等待...", "正在解析Bin");
                BinInList = new List<BinBase>();
                UpdateProgressBar(0);

                BinInList = BinHelp.BinToList(sfd.FileName);
                UpdateProgressBar(10);
                xc151_exManager xcmex = new xc151_exManager();
                var xclist = JsonConvert.DeserializeObject<List<xc151binparsing>>(xcmex.GetListToXc151Binparsing()).OrderBy(c => c.Id).ToList();
                BinHelp.BinBaseToNode(BinInList, xclist);
                UpdateProgressBar(20);
                BinInList = BinHelp.BinBaseToIsp(BinInList);
                UpdateProgressBar(30);
                BinHelp.SetModeIsp(ref BinInList);
                UpdateProgressBar(80);
                var tlist = BinInList.Where(c => !string.IsNullOrEmpty(c.note) && c.note.Contains("setting区1_31_") && !c.note.Contains("_en") && !c.module.Contains("Header")).ToList();

                if (tlist.Count() > 0)
                {
                    Setting1_31Parser s1_31 = new Setting1_31Parser();
                    s1_31.LoadSettingData(tlist.Select(c => c.original).ToList());
                    usbInList = s1_31.GetFileIDInfo();
                    UpdateProgressBar(100);
                    if (isTest)
                    {
                        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        string fulliPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "usbtest");
                        if (!Directory.Exists(fulliPath))
                        {
                            Directory.CreateDirectory(fulliPath);
                        }
                        StringBuilder sbI = new StringBuilder();
                        foreach (var item in usbInList)
                        {
                            sbI.Append($"{item.width} {item.height} {item.Type} {item.note}\r\n");
                        }
                        fulliPath = Path.Combine(fulliPath, "inList已有.txt");
                        File.WriteAllText(fulliPath, sbI.ToString());
                    }
                    var listIn = BinInList.Where(c => c.module == "Header").ToList();
                    var inCKeys = listIn.Find(c => c.address == "0x0014").original.ToString("X2") +
                    listIn.Find(c => c.address == "0x0015").original.ToString("X2") +
                    listIn.Find(c => c.address == "0x0016").original.ToString("X2") +
                    listIn.Find(c => c.address == "0x0017").original.ToString("X2");

                    if (inCKeys != "00000000")
                    {
                        newbin_btn.Enabled = false;
                        labelControl24.Visible = true;
                        CKeys.Visible = true;
                    }
                    else
                    {
                        labelControl24.Visible = false;
                        CKeys.Visible = false;
                    }
                    if (listIn.Find(c => c.address == "0x0008").original != 0x5d)
                    {
                        FlashModes = listIn.Find(c => c.address == "0x000A").original;
                        FlashKeys.Visible = true;
                    }
                    else
                    {
                        FlashKeys.Visible = false;
                    }
                }
                else
                {

                    UpdateProgressBar(0);
                    MessageBox.Show("Bin文件中不存在1_31文件，无法完成Bin解析工作，请检查Bin文件！");
                    return;
                }
                //VerifyFlashCommunicationEncryption();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                WaitBefore.Close();
            }
        }

        /// <summary>
        /// 生成新的Bin
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            if (implement_Btn.Enabled == false)
            {
                return;
            }
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "BIN文件（*.bin）|*.bin";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            //设置文件名
            sfd.FileName = "XChipNewbin_" + DateTime.Now.ToString("yyyyMMddHHmms");
            var Save_BIN_Output_File_FileName_Path = string.Empty;

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                Save_BIN_Output_File_FileName_Path = sfd.FileName.ToString();
                BinHelp.BinOutFile(Save_BIN_Output_File_FileName_Path, BinOutList);
                DevExpress.XtraEditors.XtraMessageBox.Show("导出完成");

            }
        }
        /// <summary>
        /// 执行操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            //IQ_common2 > IQ_Setting > IQ_Common1
            if (BinInList.Count <= 0)
            {
                MessageBox.Show("请导入已有的Bin文件");
                return;
            }
            if (BinOutList.Count <= 0)
            {
                MessageBox.Show("请导入目标的Bin文件");
                return;
            }
            //根据usbInList 连接关系  和usbOutList 的连接关系进行比较  找到对应文件  更新IQ中的内容 IQ_common2 > IQ_Setting > IQ_Common1

            //找到usbOutList（目标） 中 usbInList(已有) 拥有的宽度和高度  
            //增加1_31文件输出对比  当前问到的1_31 
            //根据xfw文件生成，这导致存在的问题的是xfw文件内容一致，
            //1_31解析出来的setting文件内容都会是一样 导致软件这边对处理IQ效果只能采取对应的地址编号去更改,但是询问到的结果处理是IQ_common2+ IQ_Setting + IQ_Common1进行文件处理工作，否则有偏差

            //用来记录需要更新的临时文件     2_[0]_IQ_Common1  2_[31]_IQ_common2  这两个文件 结合setting文件 进行更新   type = IQ_Common  width = 0  height = 0
            if (!VerifyFlashCommunicationEncryption())
            {
                return;
            }
            
            List<SettingFileIDInfo> listTemp = new List<SettingFileIDInfo>();
            progressBar.Properties.Maximum = usbOutList.Count();
            int proNo = 1;
            foreach (var item in usbOutList)
            {
                UpdateProgressBar(proNo++);
                //过滤掉IQ_Common 里面
                if (item.Type == SettingFileType.IQ_Common && item.width == 0 && item.height == 0) continue;

                if (usbInList.Exists(c => c.width == item.width && c.height == item.height && (c.Type == SettingFileType.IQ_Common || c.Type == SettingFileType.IQ_Config)))
                {
                    if (!listTemp.Exists(c => c.width == item.width && c.height == item.height && (c.Type == SettingFileType.IQ_Common || c.Type == SettingFileType.IQ_Config)))
                    {
                        listTemp.Add(usbInList.Find(c => c.width == item.width && c.height == item.height && (c.Type == SettingFileType.IQ_Common || c.Type == SettingFileType.IQ_Config)));


                        List<BinBase> lspINList = new List<BinBase>();
                        List<BinBase> lspOUTList = new List<BinBase>();
                        //这里需要进行判断in 和out 是否都包含Setting部分  不包含就不做处理 从输出的数据分析始终要包含IQ_Common  每套都会有，但是Setting数据不一定存在，这里没有更多的信息可以来处理Setting 信息
                        //备注：根据头文件也无法处理Setting信息，只有使能开关，未记录Setting存放的是什么制式，xfw只记录了.h文件生成的setting信息，而实际加载setting信息是没有记录的，这里导致处理这段逻辑需要注意，当前没有办法进行更改。
                        //需要拿到IQ_Common
                        var usbTInL = usbInList.Where(c => (c.width == item.width && c.height == item.height && (c.Type == SettingFileType.IQ_Common || c.Type == SettingFileType.IQ_Config)) || (c.width == 0 && c.height == 0 && (c.Type == SettingFileType.IQ_Common || c.Type == SettingFileType.IQ_Config))).ToList();
                        var usbTOutL = usbOutList.Where(c => (c.width == item.width && c.height == item.height && (c.Type == SettingFileType.IQ_Common || c.Type == SettingFileType.IQ_Config)) || (c.width == 0 && c.height == 0 && (c.Type == SettingFileType.IQ_Common || c.Type == SettingFileType.IQ_Config))).ToList();
                        if (usbTInL[1].note.Contains("setting区2_31")) continue;
                        if (usbTOutL[1].note.Contains("setting区2_31")) continue;
                        //判断usbIN 和Out 是否都存在setting   有一方不存在则不进行加载，都存在则进行加载，为了处理上面编写的逻辑
                        //1.0经过测试 这下面一段好像是无效代码 跟实际有出入，需要继续优化代码
                        if (!usbTInL.Exists(c => c.note.Contains("setting区")) && !usbTOutL.Exists(c => c.note.Contains("setting区")))
                        {
                            continue;
                        }
                        //2.0 查找Bin 是否存在setting文件
                        if (!BinInList.Exists(c => null != c.note && c.note.Contains(usbTInL[1].note))
                            && !BinOutList.Exists(c => null != c.note && c.note.Contains(usbTOutL[1].note)))
                        {
                            continue;
                        }

                        foreach (var item1 in usbTInL)
                        {
                            lspINList.AddRange(BinInList.Where(c => null != c.note && c.note.Contains(item1.note)));

                        }
                        foreach (var item2 in usbTOutL)
                        {
                            lspOUTList.AddRange(BinOutList.Where(c => null != c.note && c.note.Contains(item2.note)));

                        }
                        //把usbInList 数据替换到usbOutList
                        //新增setting 是否是文件内容  用来区分是不是setting文件内容
                        var tinList = lspINList.Where(c => c.IsSetting == true).Select(c => c.addrsmallex).ToList();
                        var toutList = lspOUTList.Where(c => c.IsSetting == true).Select(c => c.addrsmallex).ToList();

                        if (isTest)
                        {   //用来检测每个setting集合了IQ_Common 文件的输出对比，值关心尺寸对比setting, item.note 不具备参考价值，in 和out 的信息有可能不对称。
                            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                            string fulliPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "usbtest");
                            if (!Directory.Exists(fulliPath))
                            {
                                Directory.CreateDirectory(fulliPath);
                            }
                            var fulliPath1 = Path.Combine(fulliPath, $"{usbTInL[1].note}-{usbTOutL[1].note}tinList已有.txt");
                            var fulliPath2 = Path.Combine(fulliPath, $"{usbTInL[1].note}-{usbTOutL[1].note}toutList目标.txt");
                            File.WriteAllText(fulliPath1, string.Join(",\r\n", tinList));
                            File.WriteAllText(fulliPath2, string.Join(",\r\n", toutList));
                        }
                        //用于记录替换的寄存器信息处理过程，检查是否更新出现错误。
                        StringBuilder sb = new StringBuilder();
                        //用来存储历史处理过的数据进行过滤
                        List<string> HistoryList = new List<string>();
                        for (int i = 0; i < tinList.Count; i++)
                        {
                            if (HistoryList.Exists(c => c == tinList[i]))
                            {
                                continue;
                            }
                            if (tinList[i].Length < 8
                                || CheckLastFourCharacters(tinList[i].ToUpper(), "5843")
                                //|| CheckLastFourCharacters(tinList[i].ToUpper(), "0000")
                                || CheckLastFourCharacters(tinList[i].ToUpper(), "FFF5")
                                || CheckLastFourCharacters(tinList[i].ToUpper(), "F6F5")
                                || CheckLastFourCharacters(tinList[i].ToUpper(), "FFFD")
                                || CheckLastFourCharacters(tinList[i].ToUpper(), "FFFE")
                                || CheckLastFourCharacters(tinList[i].ToUpper(), "FFF8")
                                || CheckLastFourCharacters(tinList[i].ToUpper(), "FFF9")
                                || CheckLastFourCharacters(tinList[i].ToUpper(), "FFF7")
                              )
                            {
                                continue;
                            }
                            if (i == 4536)
                            {

                            }
                            //地址 需要往后查找地址
                            var addrT = tinList[i];
                            if (addrT.Contains("80300000"))
                            {

                            }
                            var sList = lspINList.Where(c => c.addrsmallex.ToLower().Contains(addrT.ToLower()) && usbTInL.Exists(b => c.note.Contains(b.note))).ToList();
                            HistoryList.Add(addrT);
                            var index = BinInList.IndexOf(sList.Last());
                            var binModel = BinInList[index];
                            byte[] bTemp = new byte[4];
                            if (binModel.IsIsp == true)
                            {
                                bTemp[0] = binModel.original;
                            }
                            else
                            {
                                var sortList = sList.OrderBy(c => c.sort).Select(c => c.sort).Distinct().ToList();
                                if (sortList.Count == 1)
                                {
                                    bTemp[0] = binModel.original;
                                }
                                else if (sortList.Count == 4)
                                {
                                    var bIndex = BinInList.FindLastIndex(c => c.addrsmallex.Contains(binModel.addrsmallex) && c.note.Contains(binModel.note) && c.AddrVal == AddressValueEnum.Val);
                                    bTemp[0] = BinInList[bIndex - 1].original;
                                    bTemp[1] = BinInList[bIndex - 0].original;
                                }
                                else if (sortList.Count == 8)
                                {
                                    var BIndex = BinInList.FindLastIndex(c => c.addrsmallex.Contains(binModel.addrsmallex) && c.note.Contains(binModel.note) && c.AddrVal == AddressValueEnum.Val);
                                    bTemp[0] = BinInList[BIndex - 3].original;
                                    bTemp[1] = BinInList[BIndex - 2].original;
                                    bTemp[2] = BinInList[BIndex - 1].original;
                                    bTemp[3] = BinInList[BIndex - 0].original;
                                }
                            }
                            var soList = lspOUTList.Where(c => c.addrsmallex.ToLower().Contains(addrT.ToLower()) && usbTOutL.Exists(b => c.note.Contains(b.note))).ToList();
                            if (soList.Count == 0)
                            {

                                sb.Append($"已有 未找到地址{addrT.ToLower()}\r\n");
                                continue;
                            }
                            var soindex = BinOutList.IndexOf(soList.Last());
                            var sobinModel = BinOutList[soindex];
                            if (sobinModel.IsIsp == true)
                            {
                                var tdata = Convert.ToUInt32($"{bTemp[3].ToString("X2")}{bTemp[2].ToString("X2")}{bTemp[1].ToString("X2")}{bTemp[0].ToString("X2")}", 16);
                                sb.Append($"地址{addrT.ToLower()}  已有Val:{bTemp[3].ToString("X2")}{bTemp[2].ToString("X2")}{bTemp[1].ToString("X2")}{bTemp[0].ToString("X2")} 目标原始Val:{BinOutList[index].original.ToString("X")} 目标Val:{tdata.ToString("X")}\r\n");
                                BinOutList[soindex].original = (byte)tdata;
                                BinOutList[soindex].smalldata = tdata.ToString("X4");

                            }
                            else
                            {
                                var sortList = soList.OrderBy(c => c.sort).Select(c => c.sort).Distinct().ToList();
                                if (sortList.Count == 1)
                                {
                                    var tdata = Convert.ToUInt32($"{bTemp[3].ToString("X2")}{bTemp[2].ToString("X2")}{bTemp[1].ToString("X2")}{bTemp[0].ToString("X2")}", 16);
                                    sb.Append($"地址{addrT.ToLower()}  已有Val:{bTemp[3].ToString("X2")}{bTemp[2].ToString("X2")}{bTemp[1].ToString("X2")}{bTemp[0].ToString("X2")} 目标原始Val:{BinOutList[index].original.ToString("X")} 目标Val:{tdata.ToString("X")}\r\n");
                                    BinOutList[soindex].original = (byte)tdata;
                                    BinOutList[soindex].smalldata = tdata.ToString("X4");
                                }
                                if (sortList.Count == 4)
                                {

                                    var bIndex = BinOutList.FindLastIndex(c => c.addrsmallex.Contains(sobinModel.addrsmallex) && c.note.Contains(sobinModel.note) && c.AddrVal == AddressValueEnum.Val);
                                    sb.Append($"地址{addrT.ToLower()}  已有Val:{bTemp[3].ToString("X2")}{bTemp[2].ToString("X2")}{bTemp[1].ToString("X2")}{bTemp[0].ToString("X2")} 目标原始Val:[{ BinOutList[bIndex - 1].original.ToString("X")}][{BinOutList[bIndex - 0].original.ToString("X")}] 目标Val:[{ bTemp[0].ToString("X")}][{ bTemp[1].ToString("X")}]\r\n");

                                    BinOutList[bIndex - 1].original = bTemp[0];
                                    BinOutList[bIndex - 0].original = bTemp[1];
                                }
                                else if (sortList.Count == 8)
                                {
                                    var BIndex = BinOutList.FindLastIndex(c => c.addrsmallex.Contains(binModel.addrsmallex) && c.note.Contains(binModel.note) && c.AddrVal == AddressValueEnum.Val);

                                    sb.Append($"地址{addrT.ToLower()}  已有Val:{bTemp[3].ToString("X2")}{bTemp[2].ToString("X2")}{bTemp[1].ToString("X2")}{bTemp[0].ToString("X2")} 目标原始Val:[{  BinOutList[BIndex - 3].original.ToString("X") }][{ BinOutList[BIndex - 2].original.ToString("X") }][{  BinOutList[BIndex - 1].original.ToString("X") }][{ BinOutList[BIndex - 0].original.ToString("X") }]目标Val:[{ bTemp[3].ToString("X")}][{ bTemp[2].ToString("X")}][{ bTemp[1].ToString("X")}][{ bTemp[0].ToString("X")}]\r\n");

                                    BinOutList[BIndex - 3].original = bTemp[3];
                                    BinOutList[BIndex - 2].original = bTemp[2];
                                    BinOutList[BIndex - 1].original = bTemp[1];
                                    BinOutList[BIndex - 0].original = bTemp[0];
                                }
                            }


                        }

                        if (isTest)
                        {   //用来检测每个setting集合了IQ_Common 文件的输出对比，值关心尺寸对比setting, item.note 不具备参考价值，in 和out 的信息有可能不对称。
                            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                            string fulliPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "usbtest");
                            if (!Directory.Exists(fulliPath))
                            {
                                Directory.CreateDirectory(fulliPath);
                            }
                            var fulliPath1 = Path.Combine(fulliPath, $"{usbTInL[1].note}-{usbTOutL[1].note}寄存器记录.txt");
                            File.WriteAllText(fulliPath1, sb.ToString());
                        }

                    }

                }
            }

            StringBuilder crcSb = new StringBuilder();
            for (int i = 0; i < BinOutList.Count; i++)
            {
                if (BinOutList[i].smalladdr.ToLower() == "f6f5" && BinOutList[i].IsSetting == true)
                {
                    var CrcIndex = i;

                    Byte[] crcList = new Byte[256]; //修改成256
                    for (int j = 0; j < crcList.Count(); j++)
                    {
                        crcList[j] = BinOutList[CrcIndex + j + 1].original;
                    }
                    //重新计算Crc
                    var crcData = XchipCrcCheck16(0xFFFF, crcList);
                    //赋值Crc
                    if (BinOutList[CrcIndex].original == 0xf6 && BinOutList[CrcIndex - 1].original == 0xf5) //修改成f6f5
                    {
                        crcSb.Append($"CRC更新索引：{CrcIndex}   原始值：{ BinOutList[CrcIndex - 3].original.ToString("X")}{ BinOutList[CrcIndex - 2].original.ToString("X") }  更新值 ：{crcData.ToString("X")}\r\n");
                        BinOutList[CrcIndex - 3].original = (byte)(crcData & 0xff);
                        BinOutList[CrcIndex - 2].original = (byte)(crcData >> 8 & 0xff);
                    }

                }
            }

            if (isTest)
            {   //用来检测每个setting集合了IQ_Common 文件的输出对比，值关心尺寸对比setting, item.note 不具备参考价值，in 和out 的信息有可能不对称。
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                string fulliPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "usbtest");
                if (!Directory.Exists(fulliPath))
                {
                    Directory.CreateDirectory(fulliPath);
                }
                var fulliPath1 = Path.Combine(fulliPath, $"CRC更新.txt");
                File.WriteAllText(fulliPath1, crcSb.ToString());
            }

            /*
            1.需要把已有的替换到目标的
            2.拿到已有的寄存器  找到目标的相同的寄存器
            2.1 用来记录需要更新的临时文件     2_[0]_IQ_Common1  2_[31]_IQ_common2  这两个文件 结合setting文件 进行更新   type = IQ_Common  width = 0  height = 0
            3.检查是否存在，存在替换，不存在记录  编写到日志中
            3.1更新的地址的位置是不是isp  
            3.2更新的地址是不是4位
            3.3更新的地址是不是8位
            4.Crc检测
            */
            newbin_btn.Enabled = true;
            MessageBox.Show("执行操作完成！");

        }
        #region 核验flash加密和通讯密钥加密
        /// <summary>
        /// 核验flash加密和通讯密钥加密
        /// </summary>
        //private void VerifyFlashCommunicationEncryption()
        //{
        //    //目标Bin和已选Bin是否存在数据 不存在则直接退出
        //    if (null == BinInList || null == BinOutList || BinInList.Count <= 0 || BinOutList.Count <= 0)
        //    {
        //        implement_Btn.Enabled = false;
        //        newbin_btn.Enabled = false;
        //        return;
        //    }

        //    //解析已选头文件
        //    var listIn = BinInList.Where(c => c.module == "Header").ToList();
        //    //解析目标头文件
        //    var listOut = BinOutList.Where(c => c.module == "Header").ToList();
        //    //获取目标BIN加密使能
        //    //获取已选BIN加密使能
        //    //获取目标Flash加密使能
        //    //获取已选Flash加密使能
        //    //获取目标Flash加密模式
        //    //获取已选Flash加密模式

        //    var listInEn = listIn.Where(c => (c.address == "0x0018" || c.address == "0x0008")).ToList();
        //    var listOutEn = listOut.Where(c => (c.address == "0x0018" || c.address == "0x0008")).ToList();
        //    var inCKeys = listIn.Find(c => c.address == "0x0014").original.ToString("X2")
        //        + listIn.Find(c => c.address == "0x0015").original.ToString("X2") +
        //        listIn.Find(c => c.address == "0x0016").original.ToString("X2") +
        //        listIn.Find(c => c.address == "0x0017").original.ToString("X2");

        //    if (listIn.Find(c => c.address == "0x0018").original != listOut.Find(c => c.address == "0x0018").original)
        //    {
        //        implement_Btn.Enabled = false;
        //        newbin_btn.Enabled = false;
        //        MessageBox.Show("通讯密钥存在差异性错误！");
        //        return;
        //    }

        //    if ((listIn.Find(c => c.address == "0x0014").original != listOut.Find(c => c.address == "0x0014").original)
        //        || (listIn.Find(c => c.address == "0x0015").original != listOut.Find(c => c.address == "0x0015").original)
        //        || (listIn.Find(c => c.address == "0x0016").original != listOut.Find(c => c.address == "0x0016").original)
        //        || (listIn.Find(c => c.address == "0x0017").original != listOut.Find(c => c.address == "0x0017").original))
        //    {
        //        implement_Btn.Enabled = false;
        //        newbin_btn.Enabled = false;
        //        MessageBox.Show("通讯密钥 加密地址错误！");
        //        return;
        //    }

        //    if (listIn.Find(c => c.address == "0x0008").original != listOut.Find(c => c.address == "0x0008").original)
        //    {
        //        implement_Btn.Enabled = false;
        //        newbin_btn.Enabled = false;
        //        MessageBox.Show("Flash加密存在差异性错误！");
        //        return;
        //    }
        //    if (listIn.Find(c => c.address == "0x000A").original != listOut.Find(c => c.address == "0x000A").original)
        //    {
        //        implement_Btn.Enabled = false;
        //        newbin_btn.Enabled = false;
        //        MessageBox.Show("Flash加密模式存在差异性错误！");
        //        return;
        //    }
        //    if (listIn.Find(c => c.address == "0x0008").original != 0x5d &&
        //        listOut.Find(c => c.address == "0x0008").original != 0x5d)
        //    {
        //        var tIn = $"{listIn.Find(c => c.address == "0x000F").original.ToString("X2")}{listIn.Find(c => c.address == "0x000E").original.ToString("X2")}{listIn.Find(c => c.address == "0x000D").original.ToString("X2")}{listIn.Find(c => c.address == "0x000C").original.ToString("X2")}";
        //        var tOut = $"{listOut.Find(c => c.address == "0x000F").original.ToString("X2")}{listOut.Find(c => c.address == "0x000E").original.ToString("X2")}{listOut.Find(c => c.address == "0x000D").original.ToString("X2")}{listOut.Find(c => c.address == "0x000C").original.ToString("X2")}";
        //        var inAddr = Convert.ToInt32(tIn, 16);
        //        var outAddr = Convert.ToInt32(tOut, 16);

        //        var model_in = BinInList[inAddr];
        //        var model_out = BinOutList[outAddr];

        //        var FtinList = BinInList.Skip(inAddr).Where(c => c.note == model_in.note).Select(c => c.original).ToList();
        //        var FtoutList = BinOutList.Skip(outAddr).Where(c => c.note == model_out.note).Select(c => c.original).ToList();

        //        bool areListsEqual = FtinList.SequenceEqual(FtoutList);
        //        if (!areListsEqual)
        //        {
        //            implement_Btn.Enabled = false;
        //            newbin_btn.Enabled = false;
        //            MessageBox.Show("Flash加密 加密地址错误！");
        //            return;
        //        }
        //    }
        //    implement_Btn.Enabled = true;

        //}
        #endregion


        /// <summary>
        /// 核验单bin文件flash加密和通讯密钥加密
        /// </summary>
        private  bool VerifyFlashCommunicationEncryption()
        {
            //目标Bin和已选Bin是否存在数据 不存在则直接退出
            if (null == BinInList || null == BinOutList || BinInList.Count <= 0 || BinOutList.Count <= 0)
            {
                newbin_btn.Enabled = false;
                return false;
            }

            //解析已选头文件
            var listIn = BinInList.Where(c => c.module == "Header").ToList();
            var listInEn = listIn.Where(c => (c.address == "0x0018" || c.address == "0x0008")).ToList();
            var inCKeys = listIn.Find(c => c.address == "0x0014").original.ToString("X2")
                + listIn.Find(c => c.address == "0x0015").original.ToString("X2") +
                listIn.Find(c => c.address == "0x0016").original.ToString("X2") +
                listIn.Find(c => c.address == "0x0017").original.ToString("X2");

            if (inCKeys != "00000000")
            {
                if (CKeys.Text =="")
                {
                    MessageBox.Show("请输入通讯密钥！");
                    return false;
                }
                var vual = XChip_Common.AppHelper.XorNotEncryption(CKeys.Text).ToString("x4");
                if (Convert.ToInt64(inCKeys, 16) != Convert.ToInt64(vual, 16))
                {
                    newbin_btn.Enabled = false;
                    MessageBox.Show("通讯密钥错误！");
                    return false;
                }
            }
            if (listIn.Find(c => c.address == "0x0008").original != 0x5d)
            {
                if (FlashbyteList.Count <=0)
                {
                    MessageBox.Show("请导入Flash加密文件！");
                    return false;
                }
                var tIn = $"{listIn.Find(c => c.address == "0x000F").original.ToString("X2")}{listIn.Find(c => c.address == "0x000E").original.ToString("X2")}{listIn.Find(c => c.address == "0x000D").original.ToString("X2")}{listIn.Find(c => c.address == "0x000C").original.ToString("X2")}";
                var inAddr = Convert.ToInt32(tIn, 16);
                var model_in = BinInList[inAddr];
                var FtinList = BinInList.Skip(inAddr).Where(c => c.note == model_in.note).Select(c => c.original).ToList();
                bool areListsEqual = FtinList.SequenceEqual(FlashbyteList);
                if (!areListsEqual)
                {
                    newbin_btn.Enabled = false;
                    MessageBox.Show("Flash加密 加密地址错误！");
                    return false;
                }

            }
            return true;

        }

        static UInt16 XchipCrcCheck16(UInt16 Input, byte[] data)
        {
            UInt16 crc_reg = Input;
            for (int i = 0; i < data.Count(); i++)
            {
                var tempCount = (crc_reg ^ data[i]) & 0xff;
                crc_reg = Convert.ToUInt16((crc_reg >> 8) ^ crc16_table[tempCount]);
            }
            return Convert.ToUInt16(crc_reg & 0xFFFF);
        }



        /// <summary>
        /// crc 全局变量
        /// </summary>
        static UInt16[] crc16_table ={
          0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
          0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
          0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
          0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
          0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
          0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
          0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
          0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
          0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
          0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
          0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
          0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
          0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
          0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
          0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
          0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
          0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
          0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
          0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
          0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
          0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
          0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
          0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
          0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
          0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
          0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
          0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
          0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
          0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
          0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
          0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
          0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78,
          };



        public bool CheckLastFourCharacters(string input, string expected)
        {
            // 确保输入字符串长度足够，以避免IndexOutOfRangeException  
            if (input.Length < expected.Length)
            {
                return false;
            }

            // 获取输入字符串的后四个字符  
            string lastFour = input.Substring(input.Length - expected.Length);

            // 比较后四个字符是否和预期相同  
            return lastFour.Equals(expected, StringComparison.OrdinalIgnoreCase);
        }

        private void FlashKeys_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入TXT（*.txt）|*.txt";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() != DialogResult.OK) return;
            //读取文件内容
            List<string> strlist = XChip_Common.Setting2Help.FileProcessing(sfd.FileName);
            if (strlist.Count() >= 2)
            {

                if (strlist[0].Length == strlist[1].Length)
                {
                    StringBuilder sb = new StringBuilder();
                    if (2 != FlashModes)
                    {
                        string result = string.Join("", strlist);
                        uint[] output = new uint[result.Length / 2]; // 创建与输入长度一半的uint数组

                        for (int j = 0; j < output.Length; j++)
                        {
                            string numStr = result.Substring(j * 2, 2); // 每两个字符提取一个数字字符串
                            output[j] = Convert.ToUInt32(numStr, 16); // 将数字字符串解析为uint类型并赋值给数组元素
                        }
                        //这里存入加密数据 扩张了 
                        var KeyEntryptlist = XChip_Common.Setting2Help.KeyEntrypt(output);
                        sb.Append($"{KeyEntryptlist[1] + KeyEntryptlist[0]}");
                        sb.Append($"{KeyEntryptlist[3] + KeyEntryptlist[2]}");
                        sb.Append($"{KeyEntryptlist[5] + KeyEntryptlist[4]}");
                        sb.Append($"{KeyEntryptlist[7] + KeyEntryptlist[6]}");
                    }
                    else
                    {
                        //大小端反转
                        byte[] bTemp = new byte[4];
                        var tempUint = getUintToString(strlist[0]);
                        bTemp[0] = (byte)(tempUint & 0xff);
                        bTemp[1] = (byte)(tempUint >> 8 & 0xff);
                        bTemp[2] = (byte)(tempUint >> 16 & 0xff);
                        bTemp[3] = (byte)(tempUint >> 24 & 0xff);

                        string output = bTemp[0].ToString("X2") + bTemp[1].ToString("X2") + bTemp[2].ToString("X2") + bTemp[3].ToString("X2");

                        sb.Append($"{output}");

                        bTemp = new byte[4];
                        tempUint = getUintToString(strlist[1]);
                        bTemp[0] = (byte)(tempUint & 0xff);
                        bTemp[1] = (byte)(tempUint >> 8 & 0xff);
                        bTemp[2] = (byte)(tempUint >> 16 & 0xff);
                        bTemp[3] = (byte)(tempUint >> 24 & 0xff);
                        output = bTemp[0].ToString("X2") + bTemp[1].ToString("X2") + bTemp[2].ToString("X2") + bTemp[3].ToString("X2"); ;

                        sb.Append($"{output}");

                    }
                    string hexWithoutCommas = sb.ToString().Replace(" ", "");
                    FlashbyteList = new List<byte>();

                    // 每两个字符一组进行转换  
                    for (int i = 0; i < hexWithoutCommas.Length; i += 2)
                    {
                        if (i + 1 < hexWithoutCommas.Length)
                        {
                            string byteValue = hexWithoutCommas.Substring(i, 2);
                            FlashbyteList.Add(Convert.ToByte(byteValue, 16));
                        }
                    }
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("KEY文件长度有误！请检查！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("无法解析文件！请输入正确KEY文件...", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private static UInt32 getUintToString(string addr)
        {
            if (string.IsNullOrEmpty(addr))
            {
                return 0x0;
            }
            else if (addr.Contains("0x"))
            {
                var temp = addr.Replace("0x", "").Trim();
                return Convert.ToUInt32(temp, 16);
            }
            else
            {

                return Convert.ToUInt32(addr.Trim(), 16);
            }
        }
    }
}